package com.sillyhat.project.core.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 判断网站状态的filter【网站是关闭的还是开放的】
 * OncePerRequestFilter确保每个请求只会被Filter过滤一次而不需要重复执行。
 * @author 徐士宽
 * @currentTime 2014-12-20 下午09:21:47
 */
@Component("siteStatusFilter")
public class SiteStatusFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(SiteStatusFilter.class);

    private static final String[] ignoreUrlPatterns = {"/admin/**"};
    private static final String redirectUrl = "/common/site_close";
    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
        //Setting setting = SettingUtils.get();
        //此处应该从数据库里面读取<或者从redis>
        boolean isSiteEnabled  = true;
        if (isSiteEnabled) { // 是否启用站点
            try {
                filterChain.doFilter(request, response);
            } catch (Exception e) {
                logger.error("网站状态的filter发生异常(1):{}",e);
            }
        } else {
            //例如：http://localhost:8080/news/main/list.jsp
            //request.getServletPath() == /main/list.jsp
            String url = request.getServletPath();
            if (redirectUrl.equals(url)) {
                try {
                    filterChain.doFilter(request, response);
                } catch (Exception e) {
                    logger.error("网站状态的filter发生异常(2):{}",e);
                }
                return;
            }
            for (String ignoreUrlPattern : ignoreUrlPatterns) {
                if (!antPathMatcher.match(ignoreUrlPattern, url)) {
                    continue;
                }
                try {
                    filterChain.doFilter(request, response);
                } catch (Exception e) {
                    logger.error("网站状态的filter发生异常(3):{}",e);
                }
                return;
            }
            try {
                response.sendRedirect(request.getContextPath() + redirectUrl);
            } catch (IOException e) {
                logger.error("网站状态的filter发生异常(4):{}",e);
            }
        }
    }
}

